package com.spring.boot.service;

import com.google.code.kaptcha.Constants;
import com.spring.boot.enums.LoginEnum;
import com.spring.boot.mapper.LoginMapper;
import com.spring.boot.mybatis.MybatisSession;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Ysoul on 15/11/14.
 */
@Service
public class LoginService extends MybatisSession {

    public LoginEnum login(HttpServletRequest request, String userName, String password, String captcha) {
        if (StringUtils.isEmpty(userName)) {
            return LoginEnum.USER_NAME_NULL;
        }
        if (StringUtils.isEmpty(password)) {
            return LoginEnum.PASSWORD_NULL;
        }
        if (StringUtils.isEmpty(captcha)) {
            return LoginEnum.CAPTCHA_NULL;
        }
        HttpSession session = request.getSession();
        if (!captcha.equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
            return LoginEnum.CAPTCHA_ERROR;
        }
        // 得到密码的MD5
        String MD5 = DigestUtils.md5DigestAsHex(password.getBytes());

        // 得到用户的MD5密码
        String netMD5 = this.getPasswordMD5(userName);

        if (MD5.equals(netMD5)) {
            return LoginEnum.SUCCESS;
        } else {
            return LoginEnum.PASSWORD_ERROR;
        }
    }

    public String getPasswordMD5(String userName) {
        SqlSession session = super.getSession();
        LoginMapper loginMapper = session.getMapper(LoginMapper.class);
        String ret = loginMapper.getPasswordMD5(userName);
        session.close();
        return ret;
    }

    public String toMD5(String password) {
        return null;
    }

}
